package com.banshuibao.bsb_android.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class Base64ForImg {

    // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
    public static String GetImageStr(String imgFilePath) {
        byte[] data = null;
        String s = "";
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
            // 对字节数组Base64编码
            s = Base64.encodeToString(data, Base64.NO_WRAP);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;// 返回Base64编码过的字节数组字符串
    }

    // 对字节数组字符串进行Base64解码并生成图片
    public static boolean GenerateImage(String imgStr, String imgFilePath) {
        if (imgStr == null) {// 图像数据为空
            return false;
        }

        try {
            // Base64解码
            byte[] bytes = Base64.decode(imgStr, 0);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 对图片生成的Base64格式进行片理，再生成Base64返回
    public static String GenerateImageToBase64(String imgStr, String imgFilePath) {
        if (imgStr == null) {// 图像数据为空
            return null;
        }

        try {
            // Base64解码
            byte[] bytes = Base64.decode(imgStr, 0);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();

            byte[] encode = Base64.encode(bytes, Base64.NO_WRAP);//转成Base64格式
            String imageBase64 = new String(encode);
            //Log.e("TAG", "路径+ "+out.toString() );
            //String imageBase64 = new String(bytes);
            return imageBase64;
        } catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
    }


    //图片路径转为Base64
    public static String imgToBase64(String imgPath) {

        if (imgPath == null || imgPath.length() == 0) return null;

        Bitmap bitmap = readBitmap(imgPath);
        if (bitmap == null) return null;

        int size = bitmap.getRowBytes() * bitmap.getHeight();
        int maxSize = 1024 * 1024;
        int scale = (size <= maxSize) ? 100 : size / maxSize;
        if (scale < 50) {
            scale = 90;
        } else if (scale > 100) {
            scale = 100;
        }
        ByteArrayOutputStream out = null;
        try {
            out = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, scale, out);

            out.flush();
            out.close();

            byte[] imgBytes = out.toByteArray();

            return Base64.encodeToString(imgBytes, Base64.NO_WRAP);
        } catch (Exception e) {
            return null;
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    //图片路径转为Base64
    public static String imgToBase64(String imgPath, Bitmap bitmap, String imgFormat) {
        if (imgPath != null && imgPath.length() > 0) {
            bitmap = readBitmap(imgPath);
        }
        if (bitmap == null) {
            //bitmap not found!!
        }
        ByteArrayOutputStream out = null;
        try {
            out = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

            out.flush();
            out.close();

            byte[] imgBytes = out.toByteArray();

            return Base64.encodeToString(imgBytes, Base64.DEFAULT);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            return null;
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static Bitmap readBitmap(String imgPath) {
        try {
            return BitmapFactory.decodeFile(imgPath);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            return null;
        }

    }

    public static Bitmap stringtoBitmap(String string) {
        //将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
            if ((bitmap.getWidth() * bitmap.getHeight()) > (600 * 1024)) {
                bitmap = resizeImage(bitmap, (int) (bitmap.getWidth() * 0.8), (int) (bitmap.getHeight() * 0.8));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }


    //将bitmap转base64
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = "";
        ByteArrayOutputStream bos = null;
        try {
            if (null != bitmap) {
                //    Log.e("TAG", "图片大小" + bitmap.getHeight() * bitmap.getWidth() / 1024);
                bos = new ByteArrayOutputStream();
                if ((bitmap.getWidth() * bitmap.getHeight()) <= 400 * 1024) {
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
                } else {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);//将bitmap放入字节数组流中
                }

                bos.flush();//将bos流缓存在内存中的数据全部输出，清空缓存
                bos.close();
                byte[] bitmapByte = bos.toByteArray();
                //     Log.e("TAG", "数组大小" + bitmapByte.length / 1024);
                result = Base64.encodeToString(bitmapByte, Base64.DEFAULT);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 图片缩放
     *
     * @param originalBitmap 原始的Bitmap
     * @param newWidth       自定义宽度
     * @return 缩放后的Bitmap
     */
    private static Bitmap resizeImage(Bitmap originalBitmap, int newWidth, int newHeight) {
        int width = originalBitmap.getWidth();
        int height = originalBitmap.getHeight();
        //定义欲转换成的宽、高
        //计算宽、高缩放率
        float scanleWidth = (float) newWidth / width;
        float scanleHeight = (float) newHeight / height;
        //创建操作图片用的matrix对象 Matrix
        Matrix matrix = new Matrix();
        // 缩放图片动作
        matrix.postScale(scanleWidth, scanleHeight);
        //旋转图片 动作
        //matrix.postRotate(45);
        // 创建新的图片Bitmap
        Bitmap resizedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, width, height, matrix, true);
        return resizedBitmap;
    }
}